package gotlib

import (
	"errors"
	"strings"
	"time"
)

func StringToDate(str string) (dt time.Time, err error) {
	// yyyy-m-d, yyyy.m.d, yyyymmdd, yyyy/m/d => yyyy/mm/dd
	// m-d-yyyy, m.d.yyyy, yyyymmdd, m/d/yyyy => yyyy/mm/dd

	sSourceFlag := "-"
	sFlag := "/"
	sDT := ""
	if strings.Index(str, "/") > 0 {
		sSourceFlag = "/"
	} else if strings.Index(str, "-") > 0 {
		sSourceFlag = "-"
	} else if strings.Index(str, ".") > 0 {
		sSourceFlag = "."
	} else {
		sSourceFlag = ""
	}

	if sSourceFlag == "" {
		if len(str) == 8 {
			sDT = strings.Join([]string{str[:4], str[4:6], str[6:]}, sFlag)
		} else {
			return dt, errors.New("date Format Error")
		}
	} else {
		arr := strings.Split(str, sSourceFlag)
		if len(arr) != 3 {
			return dt, errors.New("date Format Error")
		}
		if len(arr[0]) == 4 {
			sYear := arr[0]
			sMonth := arr[1]
			sDay := arr[2]
			if len(sMonth) == 1 {
				sMonth = "0" + sMonth
			} else if len(sMonth) != 2 {
				return dt, errors.New("date Format Error")
			}
			if len(sDay) == 1 {
				sDay = "0" + sDay
			} else if len(sDay) != 2 {
				return dt, errors.New("date Format Error")
			}
			sDT = strings.Join([]string{sYear, sMonth, sDay}, sFlag)
		} else if len(arr[2]) == 4 {
			sYear := arr[2]
			sMonth := arr[0]
			sDay := arr[1]
			if len(sMonth) == 1 {
				sMonth = "0" + sMonth
			} else if len(sMonth) != 2 {
				return dt, errors.New("date Format Error")
			}
			if len(sDay) == 1 {
				sDay = "0" + sDay
			} else if len(sDay) != 2 {
				return dt, errors.New("date Format Error")
			}
			sDT = strings.Join([]string{sYear, sMonth, sDay}, sFlag)
		} else {
			return dt, errors.New("date Format Error")
		}
	}

	return time.Parse("2006/01/02", sDT)

}
